var grid;
var form;
var form1;
$(function () {

    $(".select2").select2();

    var flag = false;
    //分配权限
    if (localStorage.getItem("roleId") == 1) {
        //管理员具有所有权限，不做任何操作
    } else if (localStorage.getItem("roleId") == 4) {
        //超级管理员具有所有权限，不做任何操作
    } else {
        //教师、学生具有的权限基本相同、包括通知的查看、基本信息的查看、编辑、修改密码
        flag = true;
        $("#addNewBtn").css('display', 'none');
        $("#skipNoticeTrash").css('display', 'none');
    }

    var pageNo = 1;
    var pageSize = 10;
    var grid_selector = "#grid-table";
    var pager_selector = "#grid-pager";
    //初始化数据表格
    grid = $(grid_selector).jqGrid({
        datatype: "json",
        url: '../InformManagement/getAllNotice',
        mtype: 'GET',
        page: pageNo,
        postData: {
            "name": $("#searchTitle").val(),
        },
        height: 380,
        width: 300,
        colNames: ['标题', '通知内容', '添加时间', "操作"],
        colModel: [
            {name: 'name', index: 'name', sortable: false, align: 'center', width: 150},
            {name: 'content', index: 'content', sortable: false, align: 'center', width: 400},
            {name: 'timeStr', index: 'timeStr', sortable: false, align: 'center', width: 200},
            {
                name: 'id', index: 'id', fixed: true, sortable: false, resize: false, width: 200,
                formatter: function (cellvalue, options, rowObject) {
                    if (flag != true)
                        return "<button class='btn btn-primary btn-xs' onclick='openShow(\"" + rowObject.id + "\")'><i class='fa fa-reddit button-in-i'></i>查看</button>"
                            + "<button class='btn btn-twitter btn-xs' onclick='openEdit(\"" + rowObject.id + "\")'><i class='fa fa-reddit button-in-i'></i>编辑</button>"
                            + "<button class='btn btn-danger btn-xs' onclick='openDelete(\"" + rowObject.id + "\")' ><i class='fa fa-trash button-in-i'></i>删除</button>";
                    else
                        return "<button class='btn btn-primary btn-xs' onclick='openShow(\"" + rowObject.id + "\")'><i class='fa fa-reddit button-in-i'></i>查看</button>";
                }
            },
        ],
        viewrecords: true,
        rowNum: pageSize,
        rownumbers: true,//添加左侧行号
        rowList: [10, 15, 20],
        pager: pager_selector,
        altRows: true,
        multiselect: false,
        loadComplete: function (data) {
            var table = this;
            setTimeout(function () {
                updatePagerIcons(table);
            }, 0);
            var h = $(window).height() - ($('#grid-pager')[0].offsetHeight + 15) - ($('.result-table .box')[0].offsetTop + $('.content .col-xs-12')[0].offsetTop + $('.ui-jqgrid-bdiv')[0].offsetTop + 3);
            $('.ui-jqgrid-bdiv').height(h);
            /*var h = $(window).height() - ($('#grid-pager')[0].offsetHeight + 15) - ($('.result-table .box')[0].offsetTop + $('.ui-jqgrid-bdiv')[0].offsetTop + 3);
            $('.ui-jqgrid-bdiv').height(h);*/
        },
        autowidth: true,
        jsonReader: jsonReader,   // json中代表实际模型数据的入口
        rownumWidth: 55,
        prmNames: prmNames,
        recordtext: "显示 {0} - {1} 条 , 共 {2} 条",
        emptyrecords: "没有记录",
        loadtext: "正在加载...",
        pgtext: "第 {0} 页  ,共 {1} 页"
    });
    //初始化分页条
    showNavGrid(grid_selector, pager_selector);
    //初始化信息校验表单
    form = $("#addform").validate({
        errorElement: 'div',
        errorClass: 'help-block messages',
        focusInvalid: false,
        highlight: validateHighlight,
        success: validateSuccess,
        errorPlacement: errorPlacement
    });
    form1 = $("#Editform").validate({
        errorElement: 'div',
        errorClass: 'help-block messages',
        focusInvalid: false,
        highlight: validateHighlight,
        success: validateSuccess,
        errorPlacement: errorPlacement
    });

    //添加新公告
    $("#addNewBtn").click(function () {
        addNewBtn();
    });
    //编辑
    $("#openEdit").click(function () {
        openEdit(str);
    });
    //查询
    $("#queryBtn").click(function () {
        var filters = {
            "name": $("#searchTitle").val(),
        }
        grid.jqGrid("setGridParam", {postData: filters, page: 1});
        grid.trigger('reloadGrid');
    });
    //清空
    $("#clearBtn").click(function () {
        $("#searchTitle").val("");
    });
    //保存
    $("#saveBtn").click(function () {
        doSubmit();
    });
    //回收站
    $("#skipNoticeTrash").click(function () {
        toTrash();
    });
});

//添加新公告
function addNewBtn() {
    clearForm();
    $("#editmyModal").modal();
    $("#modeltitle1").html("新建公告");
    // 隐藏id的div框
    $("#idLable").css("display", "none");
}

//跳转到回收站
function toTrash() {
    loadPage("../InformManagementTrash/skipToInformManagementTrashPage");
}

//打开查看表单
function openShow(id) {
    clearForm();
    $("#showmyModal").modal();
    $("#modeltitle").html("通知详情");
    // 隐藏id的div框
    $("#idLable1").css("display", "none");
    //Ajax请求查询编辑的信息
    var ware = $("#warehouseCodeEidt");
    $.post("../InformManagement/getAllNoticeById", {
        "id": id,
        "_method": "GET",
    }, function (data) {
        $("#noticeId").val(data[0].id);
        $("#noteTitle").val(data[0].name);
        $("#noteContent").val(data[0].content);
    })
}

//打开编辑表单
function openEdit(id) {
    clearForm();
    $("#editmyModal").modal();
    $("#modeltitle1").html("通知详情");
    // 隐藏id的div框
    $("#idLable").css("display", "none");
    //Ajax请求查询编辑的信息
    $.post("../InformManagement/getAllNoticeById", {
        "id": id,
        "_method": "GET",
    }, function (data) {
        $("#id").val(data[0].id);
        $("#name").val(data[0].name);
        $("#content").val(data[0].content);
    })
}

//保存编辑后的信息
function doSubmit() {
    $("#loading").removeClass('hide').addClass('show');
    $.post("../InformManagement/saveEidtNotice?_method=PUT", $('#Eidtform').serialize(), function (data) {
        if (data.resultCode == 201) {
            $("#loading").removeClass('show').addClass('hide');
            bootbox.alert(data.resultMessage);
        } else if (data.resultCode == 202) {
            $("#loading").removeClass('show').addClass('hide');
            bootbox.alert(data.resultMessage);
        } else if (data.resultCode == 200) {
            $("#loading").removeClass('show').addClass('hide');
            bootbox.alert(data.resultMessage);
            grid.trigger('reloadGrid');
            $('#editmyModal').modal('hide');
        }
    });
}

//删除记录
function openDelete(str) {
    array = str.split(",");
    bootbox.confirm("您确定要删除该通知吗?", function (result) {
        if (result) {
            $.post("../InformManagement/deleteByPrimaryKey", {
                "id": str,
                "_method": "DELETE",
            }, function (data) {
                if (data.resultCode = 200) {
                    bootbox.alert("删除成功！");
                } else {
                    bootbox.alert("删除失败！");
                }
                grid.trigger('reloadGrid');
            });
        }
    });
}

//导出数据为pdf
function exportData(obj) {
    if (obj < 10) {
        bdhtml = window.document.body.innerHTML;//获取当前页的html代码
        sprnstr = "<!--startprint" + obj + "-->";//设置打印开始区域
        eprnstr = "<!--endprint" + obj + "-->";//设置打印结束区域
        prnhtml = bdhtml.substring(bdhtml.indexOf(sprnstr) + 25); //从开始代码向后取html
        prnhtml = prnhtml.substring(0, prnhtml.indexOf(eprnstr));//从结束代码向前取html
        window.document.body.innerHTML = prnhtml;
        window.print();
        window.document.body.innerHTML = bdhtml;
    } else {
        window.print();
    }
}

//导出excel
function exportDataExcel(ids) {
    bootbox.confirm("确定导出数据为EXCEL吗？", function (result) {
        if (result) {
            location.href = ("../goodsInfo/exportExcel?ids=" + ids);
        }
    });
}

//清除表单
function clearForm() {
    //清空内容
    $("#id").val("");
    $("#content").val("");
    $("#name").val("");
    $("#noticeId").val("");
    $("#noteTitle").val("");
    $("#noteContent").val("");

    //清除验证状态
    $("#addform .form-group").removeClass('has-info').removeClass('has-error');
}